package me.zhengjie.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.WcsReport.WcsReportService;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.pojo.vo.AgvTaskSubmitVo;
import me.zhengjie.pojo.vo.ReturnVo;
import me.zhengjie.pojo.vo.TestVo;
import me.zhengjie.sqlservice.NestingMiddleTableService;
import me.zhengjie.sqlservice.WcsAgvIdService;
import me.zhengjie.sqlservice.WcsInboundMissionService;
import me.zhengjie.util.state.TaskStatus;
import me.zhengjie.util.state.TaskType;
import me.zhengjie.utility.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
@Slf4j
@Api
public class TestWms {
    private final WcsReportService wcsReportService;

    private final WcsAgvIdService wcsAgvIdService;

    private final AgvSendService agvSendService;

    private final NestingMiddleTableService nestingMiddleTableService;

    private final IdWorker idWorker;

    private final WcsInboundMissionService wcsInboundMissionService;


//    private final MapToBeanCopier mapToBeanCopier;

    @GetMapping("/isCodeExist/{containerCode}")
    @ApiOperation("入库查询容器是否已入库")
    //完成
    public boolean test1(@PathVariable String containerCode){
        InboundIsCodeExistDto inboundIsCodeExistDto = new InboundIsCodeExistDto();
        inboundIsCodeExistDto.setContainerCode(containerCode);
        inboundIsCodeExistDto.setNest(false);
        boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExistDto);
        return b;
    }

    @GetMapping("/inboundStorageApply/{containerCode}")
    @ApiOperation("入库储位申请创建入库任务")
    //完成
    public String test2(@PathVariable String containerCode){
        InboundIsCodeExistDto inboundIsCodeExistDto = new InboundIsCodeExistDto();
        inboundIsCodeExistDto.setContainerCode(containerCode);
        inboundIsCodeExistDto.setNest(false);
        boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExistDto);
        if (b){
            return  "该容器已存在库区";
        }


        List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(containerCode);
        InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
        inboundStorageApplyDto.setContainerCode(containerCode);
        inboundStorageApplyDto.setFloor(TaskType.ONE_FLOOR.getMessage());
        inboundStorageApplyDto.setNest(false);
        ArrayList<MaterialDao> materialDaos = new ArrayList<>();
        for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
            MaterialDao materialDao = new MaterialDao();
            BeanUtils.copyProperties(nestingMiddleTable,materialDao);
            materialDaos.add(materialDao);
        }
        inboundStorageApplyDto.setData(materialDaos);
        String destination = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
        log.info("入库申请终点储位：{}",destination);
        if (destination != null) {
            NestingMiddleTable nestingMiddleTable = nestingMiddleTables.get(0);
            WcsInboundMission wcsInboundMission = new WcsInboundMission();
            String inboundCode = String.valueOf(idWorker.nextId());
            wcsInboundMission.setInboundCode(inboundCode);
            wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
            wcsInboundMission.setContainerCode(containerCode);
            wcsInboundMission.setSource("起点");
            wcsInboundMission.setDestination(destination);
            wcsInboundMission.setContainerType(TaskType.PALLET.getStatus());
            wcsInboundMission.setCreateTime(LocalDateTime.now());
            wcsInboundMission.setUpdateTime(LocalDateTime.now());
            wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
            wcsInboundMission.setIsNest(0);
            wcsInboundMission.setIsPlc(1);
            StringBuilder sb = new StringBuilder();
            List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
            for (String materialCode : materialCodeList) {
                if (sb.length() >0){
                    sb.append(",");
                }
                sb.append(materialCode);
            }
            String materIalCode = sb.toString();
            wcsInboundMission.setMaterialCode(materIalCode);
            boolean b1 = wcsInboundMissionService.insertInbound(wcsInboundMission);
            if (!b1) {
                log.info("创建入库任务失败");
                throw new RuntimeException("创建入库任务失败");
            }
            return destination;
        }
        return "终点储位为null";
    }

    @GetMapping("/pickPlaceReport/{type}")
    //1
    public boolean test3(@PathVariable Integer type){
        takeReportDto takeReportDto = new takeReportDto();
        takeReportDto.setContainerCode("测试容器编码");
        takeReportDto.setStorageCode("储位编码");
        takeReportDto.setType(type);
        takeReportDto.setTaskType("type");
        takeReportDto.setNest(true);
        boolean b = wcsReportService.pickPlaceReport(takeReportDto);
        return b;
    }

    @GetMapping("/circleLibraryObtainPalletCode")
    public ReturnVo test4(){
        ReturnVo returnVo = wcsReportService.circleLibraryObtainPalletCode("palletCode");
        return returnVo;
    }

    @GetMapping("/emptyContainer")
    public ReturnVo test5(){
        ReturnVo returnVo = wcsReportService.emptyContainer("储位编码");
        return returnVo;
    }




    @GetMapping("/wmsInventoryInformation")
    //完成
    public TestVo test6() throws Exception {
        TestVo testVo = wcsReportService.wmsInventoryInformation("C00099");
        log.info("打印：{}", testVo);
        List<NestingMiddleTable> nestingMiddleTableList = new ArrayList<>();
        NestingMiddleTable nestingMiddleTable = new NestingMiddleTable();
        nestingMiddleTable.setItemBarCode("ITEM00003471");
        nestingMiddleTable.setInventoryQuantity(20.118383433666565);
        NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
        nestingMiddleTable1.setItemBarCode("ITEM00003561");
        nestingMiddleTable1.setInventoryQuantity(325.8826889625625);
        nestingMiddleTableList.add(nestingMiddleTable);
        nestingMiddleTableList.add(nestingMiddleTable1);
        List<MaterialDao> data = testVo.getData();
        HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
        HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
//        BeanUtils.copyProperties(nestingMiddleTableList,mesInventorySet);
//        BeanUtils.copyProperties(data,wmsInventorySet);
        for (MaterialDao datum : data) {
            InventoryContrast wmsInventory = new InventoryContrast();
            BeanUtils.copyProperties(datum,wmsInventory);
            wmsInventorySet.add(wmsInventory);
        }
        for (NestingMiddleTable middleTable : nestingMiddleTableList) {
            InventoryContrast wmsInventory = new InventoryContrast();
            BeanUtils.copyProperties(middleTable,wmsInventory);
            mesInventorySet.add(wmsInventory);
        }
        if (mesInventorySet.equals(wmsInventorySet)){
            log.info("一致");
        }else {
            log.info("不一致，wms数据：{},wcs:{}",wmsInventorySet,mesInventorySet);
        }

        return null;
    }

    @GetMapping("/cancelInboundStorage/{containerCode}")
    @ApiOperation("入库任务取消")
    //完成
    public boolean test7(@PathVariable String containerCode){
        List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(containerCode);
        if (!wcsInboundMissionList.isEmpty()){
            WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
            CancelInboundStorageDto cancelInboundStorageDto = new CancelInboundStorageDto();
            cancelInboundStorageDto.setStorageId(wcsInboundMission.getDestination());
            cancelInboundStorageDto.setContainerCode(wcsInboundMission.getContainerCode());
            Integer isNest = wcsInboundMission.getIsNest();
            if (isNest ==1){
                cancelInboundStorageDto.setNest(true);
            }else {
                cancelInboundStorageDto.setNest(false);
            }
            boolean b = wcsReportService.cancelInboundStorage(cancelInboundStorageDto);
            if (b){
                //刪除任務
                wcsInboundMissionService.updateMissionStatus(wcsInboundMission.getInboundCode(), 5);
            }
            return b;
        }
        return false;
    }

    //任务下发 点对点
//    {
//        "taskType" : "PF-FMR-COMMON",
//            "robotTaskCode" : "1372488009701789605",
//            "initPriority" : 99,
//            "targetRoute" : [ {
//        "seq" : 0,
//                "type" : "SITE",
//                "code" : "0531430AA0504935"
//    }, {
//        "seq" : 1,
//                "type" : "SITE",
//                "code" : "0536425AA0504935"
//    } ]
//    }

    //任务下发启点 中间点 终点
    //{
    //  "taskType" : "PF-FMR-TASK-CONTINUE",
    //  "robotTaskCode" : "1372488009701789691",
    //  "initPriority" : 99,
    //  "targetRoute" : [ {
    //    "seq" : 0,
    //    "type" : "SITE",
    //    "code" : "0525755AA0509250"
    //  }, {
    //    "seq" : 1,
    //    "type" : "SITE",
    //    "code" : "0523569AA0509300"
    //  } ]
    //}

    //链条机 0523569AA0509300 0521507AA0509490
    @PostMapping("/agvTaskSubmit")
    public String test8(@RequestBody AgvTaskSubmitDto agvTaskSubmitDto){
        String s = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
        return s;
    }

    //{
    //  "triggerCode" : "A02",
    //  "robotTaskCode" : "125465fd",
    //  "triggerType" : "SITE",
    //  "targetRoute" : {
    //    "code" : "A02",
    //    "type" : "SITE",
    //    "seq" : 1
    //  }
    //}
    //任务继续执行
    @PostMapping("/agvTaskContinueExecuteDtof")
    public boolean test9(@RequestBody AGVTaskContinueExecuteDto agvTaskContinueExecuteDto){
        boolean b = agvSendService.taskContinueExecute(agvTaskContinueExecuteDto);
        return b;
    }

    //{
    //  "siteCode" : "lift01",
    //  "taskCode" : "124353",
    //  "actionStatus" : "rtew",
    //  "eqptCode" : "ytr"
    //}
    //外设执行通知接口 1楼电梯电梯点位0540010AA0506055 2楼电梯点位0500000BB0500000电梯点  0500000BB0501590 2楼出电梯点 0502700BB0501590
    @PostMapping("/noticeAgv")
    public String test10(@RequestBody NoticeAgvDto noticeAgvDto){
        boolean b = agvSendService.noticeAgv(noticeAgvDto);
        if (b){
            return "成功";
        }
        return "失败";
    }


    //任务取消
    @PostMapping("/taskCancel")
    public AgvTaskSubmitVo taskCancel(@RequestBody TaskCancelDto taskCancelDto){
        AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskCancel(taskCancelDto);
        return agvTaskSubmitVo;
    }

    //储位绑定栈板 0531430AA0504935   0521507AA0509490
    @PostMapping("/carrierUnbind")
    public AgvTaskSubmitVo carrierUnbind(@RequestBody CarrierUnbindDto carrierUnbindDto){
        AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.carrierUnbind(carrierUnbindDto);
        return agvTaskSubmitVo;
    }

    //鼎升AGV点对点任务先绑定栈板储位
    @PostMapping("/dingsheng")
    public AgvTaskSubmitVo dingsheng(@RequestBody DingshengDto dingshengDto){
        AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.dingsheng(dingshengDto);
        return agvTaskSubmitVo;
    }
}
